//
//  EJSSettleViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/19.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSSettleViewController.h"
#import "EJSSettleGoodsCell.h"
#import "EJSSettleSelectAddressCell.h"
#import "EJSSettleFooterView.h"
#import "EJSPayOrderViewController.h"
#import "EJSManageAddressViewController.h"
#import "EJSCouponViewController.h"
#import "EJSDefaultAddressRequest.h"
#import "EJSPrepareOrderRequest.h"
#import "EJSCreateOrderRequest.h"
#import "JSONKit.h"
#import <UIView+BlocksKit.h>
#import "XOOrderInfoCell.h"
#import "XOCartPaymentViewController.h"

@interface EJSSettleViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *couponLabel;
@property (weak, nonatomic) IBOutlet UILabel *rebateLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;

@property (strong, nonatomic) EJSSettleFooterView *footerView;

@property (strong, nonatomic) EJSCouponModel *couponModel;
@property (strong, nonatomic) EJSAddressModel *defaultAddress;

@property (strong, nonatomic) EJSPrepareOrderModel *prepareOrderModel;

@property(nonatomic, strong) NSMutableArray * orderInfosTiles;
@property(nonatomic, strong) NSMutableArray * operationInfos;
@property (weak, nonatomic) IBOutlet UIButton *settleButton;

@end

@implementation EJSSettleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单支付";
    [self configBottomView];
//    [self prepareOrderRequest];
    [self getDefaultAddress];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



#pragma section 1 的 titles
- (NSMutableArray *)orderInfosTiles {
    if (_orderInfosTiles != nil) {
        return _orderInfosTiles;
    }
    NSArray * arr = @[@"小计", @"折扣",@"运费" ,@"合计"];
    _orderInfosTiles = [NSMutableArray arrayWithArray:arr];
    return _orderInfosTiles;
}

#pragma section 2 的 title 和 image
-(NSMutableArray *)operationInfos {
    if (_operationInfos != nil) {
        return _operationInfos;
    }
    NSDictionary *cupon = [NSDictionary dictionaryWithObjectsAndKeys:@"cupon_icon",@"image",@"无代金劵",@"title", nil];
//    NSDictionary *payment = [NSDictionary dictionaryWithObjectsAndKeys:@"payment_icon",@"image",@"付款方式",@"title", nil];
    _operationInfos = [NSMutableArray arrayWithObjects:cupon , nil];
    return _operationInfos;
}

- (EJSSettleFooterView *)footerView{
    if(!_footerView){
        _footerView = [[UINib nibWithNibName:@"EJSSettleFooterView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    }
    return _footerView;
}

- (void)configOwnViews
{
    [self.tableView registerNib:[UINib nibWithNibName:@"XOOrderInfoCell" bundle:nil] forCellReuseIdentifier:@"XOOrderInfoCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EJSSettleSelectAddressCell" bundle:nil] forCellReuseIdentifier:@"EJSSettleSelectAddressCell"];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    self.tableView.tableFooterView = [UIView new];
}

- (void)setPrepareOrderModel:(EJSPrepareOrderModel *)prepareOrderModel{
    if(_prepareOrderModel != prepareOrderModel){
        _prepareOrderModel = prepareOrderModel;
        [self.tableView reloadData];
    }
}


- (void)configBottomView{
    self.settleButton.layer.cornerRadius = 24.5;
    self.settleButton.layer.shadowRadius = 3;
    self.settleButton.layer.shadowColor = AppMainColor.CGColor;
    self.settleButton.layer.shadowOpacity = 0.5;
    self.settleButton.layer.shadowOffset = CGSizeMake(0, 2);

}

- (void)setCouponModel:(EJSCouponModel *)couponModel{
    if(_couponModel != couponModel){
        _couponModel = couponModel;
        _couponLabel.text = [NSString stringWithFormat:@"代金券：€ %.2f",_couponModel.amount.floatValue];
        [self prepareOrderRequest];
    }
}

- (void)getDefaultAddress{
    EJSDefaultAddressRequest *req = [EJSDefaultAddressRequest new];
    FlyWeakSelf;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        if (response.data) {
            weakSelf.defaultAddress = response.data;
        }else {
            [weakSelf showAlertForNullAdress];
        }
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

    // MARK: - Show Alert
- (void)showAlertForNullAdress{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"无默认地址" message:@"搜索不到默认地址,请选择或者新增一个默认地址" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后在选" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    
    [alertVc addAction:action];
    [alertVc addAction:cancelAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)setDefaultAddress:(EJSAddressModel *)defaultAddress{
    if(_defaultAddress != defaultAddress){
        _defaultAddress = defaultAddress;
        [self prepareOrderRequest];
    }
}


//结算第一步 准备订单 根据地址id 商品列表 获取邮费 获取 可使用优惠券
- (void)prepareOrderRequest{
    NSMutableArray *cartIds = [NSMutableArray array];
    for (EJSShoppingCartGoodsModel *cartModel in self.settleGoods) {
        if(cartModel.cartId){
            [cartIds addObject:cartModel.cartId];
        }
    }
    EJSPrepareOrderRequest *req = [EJSPrepareOrderRequest new];
    req.carts = [cartIds JSONString];
    req.addressId = self.defaultAddress.addressId;
    req.couponUserId = self.couponModel.couponUserId;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.prepareOrderModel = response.data;
    } failHandler:^(BaseResponse *response) {
        if (response.code == 2003) {
            [HUDHelper alert:response.message];
        }else{
            [[HUDHelper sharedInstance] tipMessage:response.message];
        }
    }];
}

- (IBAction)settleAction:(UIButton *)sender {
    if(!self.defaultAddress){
        [[HUDHelper sharedInstance] tipMessage:@"请选择收货地址"];
        return;
    }
    
    NSMutableArray *cartIds = [NSMutableArray array];
    
    for (EJSShoppingCartGoodsModel *cartModel in self.settleGoods) {
        if(cartModel.cartId){
            [cartIds addObject:cartModel.cartId];
        }
    }
   
    EJSCreateOrderRequest *createOderReq = [EJSCreateOrderRequest new];
    createOderReq.addressId = self.defaultAddress.addressId;
    createOderReq.couponUserId = self.couponModel.couponUserId;
    createOderReq.user_remark = self.footerView.messageTextView.text;
    createOderReq.carts =  [cartIds JSONString];
    createOderReq.shareFromToken = [[NSUserDefaults standardUserDefaults] objectForKey:AppShareFromToken];
    [createOderReq asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        EJSPayOrderViewController *payOrderVC = [[EJSPayOrderViewController alloc] initWithNibName:@"EJSPayOrderViewController" bundle:nil];
        payOrderVC.orderModel = response.data;
        payOrderVC.isNeedPopToRoot = YES;
        [self.navigationController pushViewController:payOrderVC animated:YES];
    } failHandler:^(BaseResponse *response) {
        if (response.code == 2003) {
            [HUDHelper alert:response.message];
        }else{
            [[HUDHelper sharedInstance] tipMessage:response.message];
        }
    }];
}

#pragma mark - TabelViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.orderInfosTiles.count;
            break;
        case 2:
            return self.operationInfos.count;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return 65;
    }
    return 49;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        EJSSettleSelectAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EJSSettleSelectAddressCell" forIndexPath:indexPath];
        if(self.defaultAddress){
            cell.selectAddressView.hidden = YES;
            cell.nameLabel.text = [NSString stringWithFormat:@"%@   %@ %@",self.defaultAddress.man,[EJSUserModel countryCode],self.defaultAddress.phone];
            cell.addressLabel.text = [NSString stringWithFormat:@"%@ %@",[self.defaultAddress.areaJson componentsJoinedByString:@" "],self.defaultAddress.address];

        }else{
            cell.selectAddressView.hidden = NO;
        }
        return cell;
    }else if (indexPath.section == 1){
        XOOrderInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XOOrderInfoCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.orderInfosTiles[indexPath.row];
        switch (indexPath.row) {
            case 0:
                cell.valueLabel.text = [NSString stringWithFormat:@"%@ €" ,self.prepareOrderModel.totalFee];
                break;
            case 1:
                cell.valueLabel.text = [NSString stringWithFormat:@"%@ €" ,self.prepareOrderModel.totalDiscount];
                break;
            case 2:
                cell.valueLabel.text = [NSString stringWithFormat:@"%@ €" ,self.prepareOrderModel.expressFee];
                break;
            case 3:
                cell.valueLabel.text = [NSString stringWithFormat:@"%@ €" ,self.prepareOrderModel.totalAmount];
            default:
                break;
        }
        return cell;
    }else {
        UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"operationCellIdentifier"];
        NSDictionary * dic = self.operationInfos[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:dic[@"image"]];
        cell.textLabel.text = dic[@"title"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = CHINESE_PingFangRegular(15);
        cell.textLabel.textColor = AppTextColor;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        return 0.01;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 2){
        return 150;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section == 2){
        [self.footerView.couponLabel bk_whenTapped:^{

        }];
        return self.footerView;
    }
    return [UIView new];
}


- (void)selectCoupon{
    if(self.prepareOrderModel.coupons.count == 0){
        [[HUDHelper sharedInstance] tipMessage:@"没有可以使用的优惠券"];
        return;
    }
    EJSCouponViewController *couponVC = [[EJSCouponViewController alloc] init];
    couponVC.dataSource = [self.prepareOrderModel.coupons mutableCopy];
    FlyWeakSelf
    [couponVC setBlock:^(EJSCouponModel *couponModel) {
        weakSelf.couponModel = couponModel;
    }];
    [self.navigationController pushViewController:couponVC animated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        EJSManageAddressViewController *addressVC = [EJSManageAddressViewController viewController];
        if(self.defaultAddress){
            EJSAddressModel *model = [EJSAddressModel new];
            model.addressId = self.defaultAddress.addressId;
            addressVC.selectedAddressModel = model;
        }
        addressVC.manageAddressType = 1;
        FlyWeakSelf
        [addressVC setBlock:^(EJSAddressModel *addressModel) {
            weakSelf.defaultAddress = addressModel;
            [weakSelf.tableView reloadData];
        }];
        [self.navigationController pushViewController:addressVC animated:YES];
    }else if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0:
                [self selectCoupon];
                break;
            case 1:
                [self selectPayment];

            default:
                break;
        }
    }
}

- (void) selectPayment {
    [[HUDHelper sharedInstance]tipMessage:@"此功能正在加紧完善中🚧" delay:1];
//    XOCartPaymentViewController *payment = [XOCartPaymentViewController new];
//    [self.navigationController pushViewController:payment animated:YES];
}

@end
